$(function () {
  const { layer, form } = layui;

  getArticleList();

  //渲染列表
  function getArticleList() {
    $.ajax({
      url: "/my/article/cates",
      method: "get",
      success(res) {
        if (res.status !== 0) return layer.msg(res.message);
        const tbodyHtml = template("tpl-table", res);
        $("tbody").html(tbodyHtml);
      },
    });
  }

  let index = null;

  //点击添加事件
  $("#btn_add").on("click", function () {
    index = layer.open({
      type: 1,
      titile: "添加类别",
      content: $("#dialog-add").html(),
      area: ["500px", "300px"],
    });
  });

  let indexEdit = null;

  //点击编辑事件
  $("tbody").on("click", ".btn-edit", function () {
    // 弹出一个修改文章分类信息的层
    indexEdit = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "修改文章分类",
      content: $("#dialog-edit").html(),
    });

    const id = $(this).data("id");
    $.ajax({
      method: "get",
      url: "/my/article/cates/" + id,
      success(res) {
        form.val("form-edit", res.data);
      },
    });
  });

  //添加事件 表单提交
  $("body").on("submit", "#form-add", function (e) {
    e.preventDefault();
    $.ajax({
      method: "post",
      url: "/my/article/addcates",
      data: $(this).serialize(),
      success(res) {
        if (res.status !== 0) return layer.msg(res.message);
        layer.msg(res.message);
        getArticleList();
        layer.close(index);
      },
    });
  });
  //修改事件 表单提交

  $("body").on("submit", "#form-edit", function (e) {
    e.preventDefault();
    $.ajax({
      method: "POST",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success(res) {
        if (res.status !== 0) return layer.msg(res.message);
        layer.msg(res.message);

        getArticleList();
        layer.close(indexEdit);
      },
    });
  });

  //绑定删除事件
  $("body").on("click", ".btn-delete", function () {
    const id = $(this).data("id");
    layer.confirm("确认删除?", { icon: 3, title: "提示" }, function (index) {
      $.ajax({
        method: "GET",
        url: "/my/article/deletecate/" + id,
        success: function (res) {
          if (res.status !== 0) {
            return layer.msg("删除分类失败！");
          }
          layer.msg("删除分类成功！");
          layer.close(index);
          getArticleList();
        },
      });
    });
  });

  //
});
